package it.univaq.mancoosi.injectors.systemconfiguration.managers.ubuntu;

import it.univaq.mancoosi.injectors.systemconfiguration.managers.IconCacheManager;
import it.univaq.mancoosi.injectors.systemconfiguration.utils.ProcessCommand;
import it.univaq.mancoosi.mancoosimm.File;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.GregorianCalendar;

public class UbuntuIconCacheManager extends IconCacheManager {
	
	protected String iconCachePath = "/usr/share/icons/hicolor";

	public UbuntuIconCacheManager() {
		super();
	}

	public static IconCacheManager getInstance() {
		if (INSTANCE == null)
			INSTANCE = new UbuntuIconCacheManager();
		return INSTANCE;
	}	

	@Override
	public void createIconCacheFromSystem() {

		try {

			iconCache.setEnv(UbuntuEnvironmentManager.getInstance().getEnvironment());
			UbuntuEnvironmentManager.getInstance().getEnvironment().setIconCache(iconCache);

			java.io.File iconCacheFile = new java.io.File(iconCachePath);
			if(iconCacheFile.exists()){
				File iconCacheModelFile = UbuntuFileSystemManager.getInstance()
				.createFile(iconCachePath);

				iconCache.setIcons(iconCacheModelFile);
				iconCache.setMtime(getMtimeUtil());
			}

		} catch (Exception err) {
			err.printStackTrace();
		}   
	}

	@Override
	public void synchronize() throws IOException {
		try {
			java.io.File iconCacheFile = new java.io.File(iconCachePath);
			if(iconCacheFile.exists()){
				if(UbuntuEnvironmentManager.getInstance().getEnvironment().getIconCache() == null){
					createIconCacheFromSystem();
				}else{
					//update mtime
					UbuntuEnvironmentManager.getInstance().getEnvironment().getIconCache().setMtime(getMtimeUtil());
				}				
			}else{
				if(UbuntuEnvironmentManager.getInstance().getEnvironment().getIconCache() != null){
					UbuntuEnvironmentManager.getInstance().getEnvironment().setIconCache(null);
					UbuntuFileSystemManager.getInstance().deleteFile(iconCachePath);					
				}
			}
		} catch (Exception err) {
			err.printStackTrace();
		} 
	}


	protected Date getMtimeUtil(){

		String[] mTime;

		try {
			java.io.File iconTheme = new java.io.File("/usr/share/icons/hicolor/icon-theme.cache");
			if (!iconTheme.exists()) return null;

			String[] cmd = {"/bin/sh",
					"-c",
			"ls -l /usr/share/icons/hicolor/icon-theme.cache"};
			BufferedReader input = ProcessCommand.getInstance().getResult(cmd);	

			mTime = input.readLine().split(" ");

			GregorianCalendar calendar = new GregorianCalendar();
			calendar.set(new Integer(mTime[5].split("-")[0]),
					(new Integer(mTime[5].split("-")[1]) -1),
					new Integer(mTime[5].split("-")[2]),
					new Integer(mTime[6].split(":")[0]),
					new Integer(mTime[6].split(":")[1]));

			return calendar.getTime();

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;		
	}

}
